package com.yuhang.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yuhang.entity.HyBill;
import com.yuhang.entity.HyUser;
import com.yuhang.service.HyBillService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yuhang
 * @since 2021-03-11
 */
@RestController
@RequestMapping("/hy-bill")
public class HyBillController {

    @Autowired
    private HyBillService hyBillService;

    @RequestMapping("/showAllBill")
    public Map<String,Object> shoAllBill(@RequestParam(value = "page",defaultValue = "1")int pageNum,
                                         @RequestParam(value = "limit",defaultValue = "8")int pageSize,
                                         @RequestParam(value = "likename",defaultValue = "")String likename){
        IPage<HyBill> page = hyBillService.selectByPage(pageNum, pageSize,likename);
        Map<String, Object> map = new HashMap<>();
        map.put("code",0);
        map.put("count",page.getTotal());
        map.put("data",page.getRecords());
        map.put("msg","");
        return map;
    }
    @RequestMapping("/showAllUserBill")
    public Map<String,Object> showAllUserBill(HttpSession session,
                                              @RequestParam(value = "page",defaultValue = "1")int pageNum,
                                              @RequestParam(value = "limit",defaultValue = "5")int pageSize){
        HyUser hyUser = (HyUser)session.getAttribute("hyUser");
        IPage<HyBill> page = hyBillService.selectByPage(pageNum, pageSize,hyUser.getId());
        Map<String, Object> map = new HashMap<>();
        map.put("code",0);
        map.put("count",page.getTotal());
        map.put("data",page.getRecords());
        map.put("msg","");
        return map;
    }

    @RequestMapping("/addBill")
    public Map<String,Object> addBill(HyBill hyBill){
        QueryWrapper<HyBill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",hyBill.getUserId()).eq("bill_date",hyBill.getBillDate());
        HyBill one = hyBillService.getOne(queryWrapper);
        if(Objects.isNull(one)){
            double allCost = hyBill.getWaterBill() + hyBill.getElectricityBill() + hyBill.getWuyeBill();
            hyBill.setAllCost(allCost);
            if(hyBill.getState()==1){
                DateTime now = DateUtil.date();
                hyBill.setPayDate(now);
            }
            hyBillService.save(hyBill);
            Map<String, Object> map = new HashMap<>();
            map.put("code",0);
            return map;
        }else {
            Map<String, Object> map = new HashMap<>();
            map.put("code",1);
            map.put("message","该月份账单已提交，请勿重复提交");
            return map;
        }

    }

    @RequestMapping("/updateBill")
    public Map<String,Object> updateBill(HyBill hyBill){
        QueryWrapper<HyBill> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",hyBill.getUserId()).eq("bill_date",hyBill.getBillDate());
        HyBill one = hyBillService.getOne(queryWrapper);
        if(Objects.isNull(one)){
            double allCost = hyBill.getWaterBill() + hyBill.getElectricityBill() + hyBill.getWuyeBill();
            hyBill.setAllCost(allCost);
            hyBillService.updateById(hyBill);
            Map<String, Object> map = new HashMap<>();
            map.put("code",0);
            return map;
        }else {
            Map<String, Object> map = new HashMap<>();
            map.put("code",1);
            map.put("message","该月份账单已提交，请勿重复提交");
            return map;
        }
    }

    @RequestMapping("/deleteBill")
    public Map<String,Object> deleteBill(Integer id){
        hyBillService.removeById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("code",0);
        return map;
    }
    @RequestMapping("/payBill")
    public Map<String,Object> payBill(Integer id){
        HyBill hyBill = hyBillService.getById(id);
        hyBill.setState(1);
        DateTime now = DateUtil.date();
        hyBill.setPayDate(now);
        hyBillService.updateById(hyBill);
        Map<String, Object> map = new HashMap<>();
        map.put("code",0);
        map.put("message","是否确认缴费,共计"+hyBill.getAllCost()+"元。");
        return map;
    }

    @RequestMapping("/paySomeBill")
    public Map<String,Object> paySomeBill(@RequestParam(value = "ids") List<Integer> ids){
        List<HyBill> hyBills = hyBillService.listByIds(ids);
        Boolean b = true;
        for (HyBill hyBill : hyBills) {
            if(hyBill.getState()==1){
                b=false;
                break;
            }
        }
        DateTime now = DateUtil.date();
        Double cost = 0.0;
        if(b){
            for (HyBill hyBill : hyBills) {
                hyBill.setState(1);
                hyBill.setPayDate(now);
                cost=hyBill.getAllCost()+cost;
            }
            hyBillService.updateBatchById(hyBills);
            Map<String, Object> map = new HashMap<>();
            map.put("code",0);
            map.put("message","缴费成功,共计"+cost+"元。");
            return map;
        }else {
            Map<String, Object> map = new HashMap<>();
            map.put("code",1);
            map.put("message","所选项中存在已缴费选项，无法重复缴费，请重新选择！！！");
            return map;
        }
    }

//    @RequestMapping("/importBill")//导入
//    public Map<String,Object> importBanner(MultipartFile file) throws Exception {
//        //        流读取文件
//        InputStream inputStream = file.getInputStream();
//        /**
//         * setTitleRows(1) 设置标题所占的行数
//         * setHeadRows(1) 设置表头所占的行数
//         */
//        ImportParams importParams = new ImportParams();
//        importParams.setTitleRows(1);
//        importParams.setHeadRows(1);
//        /**
//         * 参数1 流
//         * 参数2 pojoClass 普通Java对象的类对象 要导入的实体类的类对象
//         * 参数3 导入参数对象
//         */
//        List<HyBill> list = ExcelImportUtil.importExcel(inputStream, HyBill.class, importParams);
//        boolean b = true;
//        for (HyBill hyBill : list) {
//            QueryWrapper<HyBill> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("user_id",hyBill.getUserId()).eq("bill_date",hyBill.getBillDate());
//            HyBill one = hyBillService.getOne(queryWrapper);
//            if(one!=null){
//                b=false;
//            }
//        }
//        if (b){
//            hyBillService.saveBatch(list);
//            Map<String, Object> map = new HashMap<>();
//            map.put("code",0);
//            return map;
//        }else {
//            Map<String, Object> map = new HashMap<>();
//            map.put("code",1);
//            map.put("message","导入数据中存在账单时间重复，请核对后重新上传！！！");
//            return map;
//        }
//
//    }

    @RequestMapping("/exportBill")//导出
    public void exportBanner(@RequestParam(value = "ids") List<Integer> ids, HttpServletResponse response) throws IOException, ParseException {
        String s = ids.toString();
        response.setHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(s,"UTF-8"));
        response.setContentType("application/vnd.ms-excel");
        Collection<HyBill> list = hyBillService.listByIds(ids);
        ExportParams exportParams = new ExportParams("账单数据","bill");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, HyBill.class, list);
        //        保存到本地  自适应两种格式 xls xlsx
        workbook.write(response.getOutputStream());
    }

}
